<?php
class Zext_Plugin_Auth extends Zend_Controller_Plugin_Abstract{
    
	public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $dispatchable = Zend_Controller_Front::getInstance()->getDispatcher();
        $acl = Zend_Registry::get("acl");
        $auth = Zend_Auth::getInstance();
        
        $controller = $request->getControllerName();
        $action = $request->getActionName();
        
        $model = new Application_Model_DbTable_NghiepVu();
        $where = $model->select()->where("controller_name=?",$controller)
                                 ->where("action_name=?",$action);
        $nghiepvu = $model->fetchRow($where);
        if( !$nghiepvu && $dispatchable->isDispatchable( $request )){
            $nghiepvu = $model->createRow(array(
                'TenNghiepVu' => 'Mặc định',
                'controller_name' => $controller,
                'action_name' => $action
            ));
            $nghiepvu->save();
        }
        
        $role = new Zend_Acl_Role( $auth->hasIdentity()?$auth->getIdentity()->MaNhom:GUEST_ID );
        $resource = new Zend_Acl_Resource( $nghiepvu->MaNghiepVu );
        if($controller != "user" && !$auth->hasIdentity()){
            $request->setControllerName("user");
            $request->setActionName("login");
        }
        if($controller != "user" && !$acl->isAllowed($role,$resource)){
            $request->setControllerName("user");
            $request->setActionName("noauth");
        }
	}
    
    
}